/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import DataAccess.DataAccessFacade;
import DomainModel.ManageEmail;
import DomainModel.User;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.jasypt.util.password.BasicPasswordEncryptor;

/**
 *
 * @author Team2
 */
@WebServlet(name = "ForgotPasswordController", urlPatterns = {"/ForgotPasswordController"})
public class ForgotPasswordController extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/forgotPassword.jsp").forward(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String userEmail = request.getParameter("userEmail");

        if (userEmail != null) {
            doResetPassword(request, response);
        }
    }

    private void doResetPassword(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Prepare messages.
        Map<String, String> messages = new HashMap<>();
        request.setAttribute("messages", messages);

        String strUserEmail = request.getParameter("userEmail");
        String message = null;
        User user = null;
//        HttpSession session = request.getSession();

        try {

            user = DataAccessFacade.getInstance().getUserByEmail(strUserEmail);

            if (user != null) {
                String token = UUID.randomUUID().toString();
                Calendar cal = Calendar.getInstance();
                //expire in one hour
                cal.add(Calendar.HOUR, 1);
                java.sql.Timestamp expire_date = new java.sql.Timestamp(cal.getTimeInMillis());
                boolean generatedPasswordReset = DataAccessFacade.getInstance().generatePasswordResetForUser(user.getUserId(), token, expire_date);

                if (generatedPasswordReset) {
                    ManageEmail manageEmail = new ManageEmail();

                    //@todo This needs to match final URL of actual change password page
                    String resetPasswordURL = "http://localhost:8080/changePassword?token=" + token;

                    String messageSubject = "GRS Password Reset";
                    String messageDetail = "You have requested to have your GRS password reset...\n"
                            + "Please, click on the link, below. Link will expire in one hour.\n"
                            + "<html>" + resetPasswordURL + "</html>"
                            + " \nregards,\n Team2";

                    boolean success = manageEmail.sendHtmlEmail(user.getEmail(), messageSubject, messageDetail);
                    if (success) {
                        message = "Password reset link has been sent to your registered email.";
                        messages.put("success", message);
                    } else {
                        message = "Error sending password reset email. Please, try again.";
                        messages.put("error", message);
                    }
                } else {
                    message = "Unable to generate URL, please try again, later.";
                    messages.put("error", message);
                }
//                session.setAttribute("currentUser", user);
            } else {
                message = "Unable to find username / email in database";
                messages.put("error", message);
            }
            request.getRequestDispatcher("/forgotPassword.jsp").forward(request, response);
        } catch (Exception e) {
            message = "General error: " + e.getMessage();
            messages.put("resetPassword", message);
            request.getRequestDispatcher("/forgotPassword.jsp").forward(request, response);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Forgot Password";
    }// </editor-fold>
}
